<template>
  <div v-loading="pluginLoading" class="container">
    <!-- 插件标题和版本 -->
    <div class="title-bar">
      <h1>{{ pluginStore.pluginInfo?.name }}</h1>
      <span class="version">{{ pluginStore.pluginInfo?.version }}</span>
    </div>

    <!-- 登录状态显示 -->
    <div class="user-status" v-if="isLogin">
      <div class="user-info">
        <el-avatar :icon="User" class="avatar" />
        <span class="username">{{ username || "用户" }}</span>
      </div>
      <el-button
        type="text"
        size="small"
        class="logout-btn"
        @click="handleLogout"
      >
        退出登录
      </el-button>
    </div>

    <!-- 登录表单 -->
    <el-card class="auth-card" v-if="!isLogin">
      <div class="title">账号登录</div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            @keyup.enter="handleLogin()"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn"
            @click="handleLogin()"
            :loading="loginLoading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 功能按钮区域 (登录后显示) -->
    <el-card v-if="isLogin" :body-style="{ padding: '10px' }">
      <el-form
        ref="operateFormRef"
        label-position="left"
        label-width="100px"
        :model="operateForm"
        :rules="operateRules"
        v-loading="formLoading"
      >
        <el-form-item prop="action">
          <template #label>
            <div class="label-wrapper">
              <div>核价源</div>
              <ByTooltip
                content="选择'根据采集原价核价'如当前店铺在ERP中没有找到该SKU则跳过"
              />
            </div>
          </template>
          <el-select v-model="operateForm.action" @change="handleActionChange">
            <el-option
              v-for="item in operateTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!isMatchPlatform" label="平台" prop="platform">
          <el-select
            v-model="operateForm.platform"
            @change="handlePlatformChange"
          >
            <el-option
              v-for="item in platforms"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="isAutomaticallyAgreeToNegotiateAction"
          label="店铺"
          prop="shopId"
        >
          <el-select v-model="operateForm.shopId" v-loading="shopLoading">
            <el-option
              v-for="item in shopList"
              :key="item.id"
              :label="item.shopName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="核价动作" prop="actionType">
          <template #label>
            <div class="label-wrapper">
              <div>核价动作</div>
              <ByTooltip>
                <template #content>
                  <div>
                    1."同意核价":如果
                    {{ `${typeOriginLabel} * 倍率 <= ${typeTargetLabel}` }}
                    则自动同意核价,如果不符合则跳过
                  </div>
                  <div>
                    2."拒绝核价":如果
                    {{ `${typeOriginLabel} * 倍率 > ${typeTargetLabel}` }}
                    则自动拒绝核价,如果不符合则跳过
                  </div>
                  <div>
                    3."重新报价(倍率)":按照
                    {{ `${typeOriginLabel} * 倍率 重新报价` }}
                  </div>
                  <div>
                    4."重新报价(固定值)":按照
                    {{ `${typeOriginLabel} - 固定值 重新报价` }}
                  </div>
                </template>
              </ByTooltip>
            </div>
          </template>
          <el-select v-model="operateForm.actionType">
            <el-option
              v-for="item in actionTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="页数" prop="maxPages">
          <el-input-number v-model="operateForm.maxPages" :step="1" :min="1" />
        </el-form-item>
        <el-form-item
          :label="
            operateForm.actionType === ACTION_TYPE.AGAIN_BY_REDUCE_FIXED
              ? '固定值'
              : '价格倍率'
          "
          prop="multiplier"
        >
          <el-input-number
            v-model="operateForm.multiplier"
            :precision="2"
            :step="0.1"
            :min="0.1"
            @change="handleMultiplierChange"
          />
        </el-form-item>
      </el-form>
      <div class="btn-wrapper">
        <el-button type="primary" @click="startMaticPricing" :loading="startLoading">
          开始核价
        </el-button>
      </div>
    </el-card>

    <OutLoginDeviceReplaceDialog
      ref="outLoginDeviceReplaceDialogRef"
      @confirm="handleLogin"
    />
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  ref,
  reactive,
  computed,
  watch,
  type Ref,
  nextTick,
} from "vue";
import { usePluginStore } from "@/store/modules/plugin";
import { User } from "@element-plus/icons-vue";
import { useResetRef } from "@/hooks";
import { useUserStore } from "@/store/modules/user";
import { selectList } from "@/api/common";
import ByTooltip from "@/components/By/ByTooltip.vue";
import { checkTokenExpired } from "@/utils";
import OutLoginDeviceReplaceDialog from "@/components/OutLoginDeviceReplaceDialog.vue";
import type { TOperateForm } from "./type";
import { debounce } from "lodash-es";
import { ACTION_TYPE } from "@/constants/actionType";
import { ElMessage } from "element-plus";

const pluginStore = usePluginStore();
const userStore = useUserStore();
const outLoginDeviceReplaceDialogRef = ref();

const operateTypeOptions = ref([
  {
    label: "根据平台报价记录核价",
    value: "automaticallyAgreeToNegotiateActionByCostPrice",
  },
  {
    label: "根据采集原价核价",
    value: "automaticallyAgreeToNegotiateAction",
  },
]);
const platforms = ref([
  {
    label: "SHEIN",
    value: "shein",
  },
  {
    label: "TEMU",
    value: "temu",
  },
]);

const formLoading = ref(false);

const loginLoading = ref(false);
const loginForm = useResetRef({
  username: "",
  password: "",
  loginEntrance: "PRICE_CHECK_PLUGIN",
});
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
const loginFormRef = ref();
const startLoading = ref(false);

const operateFormRef = ref();
const operateForm: Ref<TOperateForm> = ref({
  action: operateTypeOptions.value[0].value,
  actionType: ACTION_TYPE.AGREE,
  platform: "",
  maxPages: 5,
  multiplier: 0.7,
  shopId: "",
});

const actionTypeOptions = computed(() => {
  const list = [
    {
      label: "同意核价",
      value: ACTION_TYPE.AGREE,
    },
    {
      label: "拒绝核价",
      value: ACTION_TYPE.REFUSE,
    },
    {
      label: "重新报价(倍率)",
      value: ACTION_TYPE.AGAIN,
      visible: operateForm.value.platform === "shein",
    },
    {
      label: "重新报价(固定值)",
      value: ACTION_TYPE.AGAIN_BY_REDUCE_FIXED,
      visible: operateForm.value.platform === "shein",
    },
  ];
  return list.filter((item) => {
    const { visible } = item;
    return !("visible" in item) || visible;
  });
});
const actionMultiplierStorage = computed(() => {
  const { action } = operateForm.value;
  return `baoyiplus_${action}_multiplier`;
});

const shopLoading = ref(false);
const shopList: any = ref([]);
const isMatchPlatform = ref(false);
const pluginLoading = ref(false);

const isLogin = computed(() => userStore.isLogin);
const username = computed(() => userStore.userInfo?.username);
const isAutomaticallyAgreeToNegotiateAction = computed(() => {
  const { action } = operateForm.value;
  return action === "automaticallyAgreeToNegotiateAction";
});
const typeOriginLabel = computed(() => {
  const { platform } = operateForm.value;
  if (isAutomaticallyAgreeToNegotiateAction.value) {
    return "采集原价";
  }

  if (platform === "shein") {
    return "报价记录";
  }
  return "原申报价格";
});
const typeTargetLabel = computed(() => {
  const { platform } = operateForm.value;
  if (platform === "shein") {
    return "平台建议价";
  }
  return "建议申报价";
});

const operateRules = computed(() => {
  return {
    action: [{ required: true, message: "请选择核价源", trigger: "blur" }],
    platform: [{ required: true, message: "请选择平台", trigger: "change" }],
    shopId: [
      {
        required: isAutomaticallyAgreeToNegotiateAction.value,
        message: "请选择店铺",
        trigger: "change",
      },
    ],
    actionType: [
      { required: true, message: "请选择核价动作", trigger: "change" },
    ],
    maxPages: [{ required: true, message: "请选择页数", trigger: "blur" }],
    multiplier: [
      { required: true, message: "请选择价格倍率", trigger: "blur" },
    ],
  };
});

const handleGetShopList = () => {
  const { platform } = operateForm.value;
  if (!platform) {
    return Promise.resolve();
  }
  shopLoading.value = true;
  operateForm.value.shopId = "";
  return selectList("shop", "shopInfo", { platform })
    .then((res) => {
      shopList.value = res.data;
      if (shopList.value.length > 0) {
        operateForm.value.shopId = shopList.value[0].id;
      }
    })
    .finally(() => {
      shopLoading.value = false;
    });
};

const handlePlatformChange = () => {
  handleGetShopList();
};

const tryAutoLogin = () => {
  chrome.storage.sync
    .get(["baoyiplus_accessToken", "baoyiplus_expiresIn", "baoyi_operate_form"])
    .then(async (storageData) => {
      const { baoyiplus_accessToken, baoyiplus_expiresIn, baoyi_operate_form } =
        storageData;
      if (baoyiplus_accessToken && !checkTokenExpired(baoyiplus_expiresIn)) {
        formLoading.value = true;
        await userStore.getUserInfo();
        await handleGetShopList();
        formLoading.value = false;
        const { platform } = operateForm.value;
        if (platform && platform === baoyi_operate_form.platform) {
          operateForm.value = {
            ...baoyi_operate_form,
          };
          if (
            !shopList.value.some(
              (shop: any) =>
                Number(shop.id) === Number(baoyi_operate_form.shopId)
            )
          ) {
            operateForm.value.shopId = shopList.value?.[0].id;
          }
        }
      }
    })
    .finally(() => {
      pluginLoading.value = false;
    });
};

const openOutLoginDeviceReplaceDialog = (loginLogs: any) => {
  outLoginDeviceReplaceDialogRef.value.openDialog(loginLogs);
};

const handleLogin = async (logOutId = "") => {
  const valid = await loginFormRef.value.validate();
  if (!valid) return;

  const params: any = {
    ...loginForm.value,
  };
  if (logOutId) {
    params.logOutId = logOutId;
    params.forceLogin = true;
  }
  loginLoading.value = true;
  return userStore
    .handleLogin(params)
    .then(() => {
      userStore.getUserInfo();
      handleGetShopList();
      loginForm.reset();
    })
    .catch((error) => {
      const code = error.response?.data?.code;
      const loginLogs = Object.values(error.response?.data?.paramMap || {});
      if (code === 409) {
        if(loginLogs.length) {
          openOutLoginDeviceReplaceDialog(loginLogs);
        }else {
          ElMessage.error(error.response?.data?.posterCode || "同时在线使用设备数超出限制,请登录ERP购买")
        }
      }
    })
    .finally(() => {
      loginLoading.value = false;
    });
};

const handleLogout = async () => {
  pluginLoading.value = true;
  await userStore.handleLogout();
  pluginLoading.value = false;
};

const startMaticPricing = () => {
  operateFormRef.value.validate((valid: Boolean) => {
    if (valid) {
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs && tabs[0] && tabs[0].id) {
          startLoading.value = true;
          chrome.tabs.sendMessage(tabs[0].id, operateForm.value).finally(()=> {
            startLoading.value = false;
          });
        }
      });
    }
  });
};

const handleInitPlatform = (url: any) => {
  if (url.includes("seller.kuajingmaihuo") || url.includes("temu")) {
    operateForm.value.platform = "temu";
    isMatchPlatform.value = true;
  } else if (url.includes("shein")) {
    operateForm.value.platform = "shein";
    isMatchPlatform.value = true;
  }
};

const getCurrentPageUrl = () => {
  pluginLoading.value = true;
  chrome.tabs.query(
    {
      active: true,
      currentWindow: true,
    },
    (tabs) => {
      if (chrome.runtime.lastError) {
        console.error("获取标签页失败:", chrome.runtime.lastError);
        pluginLoading.value = false;
        return;
      }

      const activeTab = tabs[0];
      if (activeTab?.url) {
        handleInitPlatform(activeTab.url);
        pluginStore.getPluginInfo();
        tryAutoLogin();
      } else {
        pluginLoading.value = false;
      }
    }
  );
};

const handleActionChange = () => {
  chrome.storage.sync.get([actionMultiplierStorage.value]).then((data) => {
    const defaultMultiplier =
      operateForm.value.action ===
      "automaticallyAgreeToNegotiateActionByCostPrice"
        ? "0.7"
        : "";
    operateForm.value.multiplier =
      data?.[actionMultiplierStorage.value] || defaultMultiplier;
    nextTick(() => {
      operateFormRef?.value?.validateField?.("multiplier");
    });
  });
};
const handleMultiplierChange = debounce((multiplier: any) => {
  chrome.storage.sync.set({
    [actionMultiplierStorage.value]: multiplier,
  });
}, 500);

watch(
  () => operateForm.value,
  (newValue) => {
    chrome.storage.sync.set({ baoyi_operate_form: newValue });
  },
  {
    deep: true,
  }
);
// 组件挂载时获取地址
onMounted(() => {
  getCurrentPageUrl();
  handleActionChange();
});
</script>

<style scoped lang="scss">
.container {
  width: 380px;
  padding: 5px;
  background-color: #fff;
}

.title-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;

  h1 {
    font-size: 18px;
    margin: 0;
    color: #333;
  }

  .version {
    font-size: 12px;
    color: #666;
    background: #f5f5f5;
    padding: 2px 6px;
    border-radius: 4px;
  }
}

.user-status {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border-radius: 6px;

  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;

    .avatar {
      background-color: #409eff;
    }

    .username {
      font-size: 14px;
      font-weight: 500;
    }
  }

  .logout-btn {
    color: #666;
    &:hover {
      color: #f56c6c;
    }
  }
}

.auth-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  .title {
    font-size: 20px;
  }
  .login-form {
    margin-top: 10px;
  }
}

.el-form {
  .label-wrapper {
    display: flex;
    align-items: center;
  }
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
  :deep(.el-form-item__content) {
    & > * {
      width: 100%;
    }
  }
}

.btn-wrapper {
  width: 100%;
  .el-button {
    width: 100%;
  }
}
</style>
